package chenji.gunapi.bullet;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;

import chenji.gunapi.GunAPI;
import chenji.gunapi.events.BulletHitBlockEvent;
import chenji.gunapi.gun.Gun;
import chenji.gunapi.task.Taskable;

public class BulletManager implements Taskable {
	public BulletManager() {
		GunAPI.getGunAPI().getGunTaskManager().registerPerTickTask(this);
	}

	private Map<Arrow, Bullet> bulletcache = new HashMap<>();
	private Set<Arrow> removeCache = new HashSet<>();

	public void shoot(Gun g, Player p, int alreadShoot) {
		System.out.println("shoot");
		Arrow bullet = (Arrow) p.launchProjectile(Arrow.class);
		bullet.setVelocity(p.getLocation().getDirection().multiply(100D));
		// bullet.setShooter(p);
		// bullet = g.setAccuracy(bullet, alreadShoot, true);
		// bullet = g.makeBullet(bullet);
		Bullet b = new Bullet(g, g.getDamage(), bullet, p);
		this.bulletcache.put(bullet, b);
	}

	public Bullet getBullet(Entity entity) {
		if (this.bulletcache.containsKey(entity)) {
			return this.bulletcache.get(entity);
		}
		return null;
	}

	public void removeBullet(Entity entity) {
		this.bulletcache.remove(entity);
		entity.remove();
	}

	public void task() {
		for (Arrow a : this.removeCache) {
			if (this.contain(a)) {
				Bullet b = this.getBullet(a);
				if (b != null) {
					if (!b.isHitEntity()) {
						this.hitBlock(b);
					}
				}
			}
			this.removeBullet(a);
		}
		this.removeCache.clear();
		return;
	}

	private void hitBlock(Bullet b) {
		Block block = b.getDamager().getTargetBlock(GunAPI.getGunAPI().getUntl().getMaterial(), 100);
		BulletHitBlockEvent e = new BulletHitBlockEvent(b.getDamager(), block);
		e.setPlayEffect(true);
		Bukkit.getPluginManager().callEvent(e);
		if (e.isCancelled()) {
			return;
		}
		if (!(e.isPlayEffect())) {
			return;
		}
		b.getDamager().getLocation().getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getType());
	}

	public void createWaitRemove(Entity e) {
		removeCache.add((Arrow) e);
	}

	public boolean contain(Projectile entity) {
		return this.bulletcache.containsKey(entity);
	}
}
